import { CACHE_MANAGER, HttpService, Inject, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AdministratorModelService } from 'src/models/administrator-model/administrator-model.service';
import { UserService } from 'src/models/user/user.service';
const moment = require('moment');
//import { RedisService } from 'src/redis/redis.service';
import { errorReturn } from 'src/utils';
const crypto = require('crypto');

@Injectable()
export class LoginService {
    constructor(
        //private redis : RedisService,
        private configService : ConfigService,
        private administratorModelService : AdministratorModelService,
        private httpService : HttpService,
        private userService : UserService
    ) {}
    async login(account:string, password:string) {
        // let r = this.redis.client.set('')


        // let currentDay = Number(moment().startOf('day').format('X')) //当天的00:00:00
        // let endDay = Number(moment().endOf('day').format('X'))
        // let loginErrorKey = account + '.login_error.' + currentDay
        // let count = await this.redis.get<number>(loginErrorKey)
        // if(count == null) count = 0

        // const maxLoginCount = this.configService.get<number>('login_max_count')

        // if(count >= maxLoginCount) return errorReturn(`今天登录失败已超过${maxLoginCount}次`)
        

        // //加个锁，防止暴力登录
        // this.redis.client.set()
        // const row = await this.administratorModelService.findOne({ account }, ['name', 'password', 'salt'])
        // if(!row || (crypto.createHash('md5').update((password + row.salt)).digest('hex').toLowerCase() !== row['password'])) {

        //     this.redis.set<number>(loginErrorKey, count + 1, 600)
        //     if(count == 0) {
        //         this.redis.client.expireat(loginErrorKey, endDay)
        //     }

        //     return errorReturn('账号不存在或密码错误')
        // }
    }

    async wechatLogin(code:string) {
        const wechat = this.configService.get('wechat')
        let { data } = await this.httpService.get(wechat.authCode2SessionUrl, {
            timeout : 1000,
            responseType : 'text',
            params : {
                appid : wechat.appid,
                secret : wechat.secret,
                js_code : wechat.js_code,
            }
        }).toPromise()

        if(typeof data !== 'object' || data.errcode !== 0) return errorReturn('请求失败')

        const { openid, session_key, unionid} = data

        let user = this.userService.findOne({unionid : unionid}, ['user_id'])
        

        //查询有无

    }
}
